//Function类库
var WebIMFun = { 
	//环信 注册
	doReg : function(user,pwd,nickname,fn){
		var options = { 
			username: user,
			password: pwd,
			nickname: nickname,
			success: function () { fn(true); },  
			error: function () { fn(false); }, 
			apiUrl: WebIM.config.apiURL,
			appKey: WebIM.config.appkey
		};
		WebIM.utils.registerUser(options);
	}, 
	//登录
	doLogin : function(user,pwd){
		var options = { 
			apiUrl: WebIM.config.apiURL,
			user: user,
			pwd: pwd,
			appKey: WebIM.config.appkey
		};   
		IMconn.open(options);
	},
	//创建群组
	createGroup : function (name,introduce) {
	    var option = {
	        subject: name,                     			// 群名称
	        description: introduce,         			// 群简介
	        members: ['', ''],               			// 以数组的形式存储需要加群的好友ID
	        optionsPublic: true,                        // 允许任何人加入
	        optionsModerate: false,                     // 加入需审批
	        optionsMembersOnly: false,                  // 不允许任何人主动加入
	        optionsAllowInvites: false                  // 允许群人员邀请
	    };
	    IMconn.createGroup(option);
	},
	// 列出所有群组
	listGroups : function () {
	    var option = {
	        success: function (rooms) {
	            console.log(rooms);
	        },
	        error: function () {
	            console.log('List groups error');
	        }
	    };
	    IMconn.listRooms(option);
	},
	//获取好友
	doGetUser : function(){ 
		IMconn.getRoster({
			success: function ( roster ) {
				PageFun.listFriend(roster);
			},
		});
	},
	//发送信息
	doSendMesTo : function(toUser,mes,fn){
		var id = IMconn.getUniqueId();
		var msg = new WebIM.message('txt', id);//创建文本消息 
		msg.set({
				msg: mes,
				to: toUser,
				success: function ( id,serverMsgId ) {
					if(fn) fn(id,serverMsgId);
				} 
			});
		IMconn.send(msg.body);
	},
	// 群组发送文本消息
	sendGroupText : function (toGroupId,mes,fn) {
	    var id = IMconn.getUniqueId();            	// 生成本地消息id
	    var msg = new WebIM.message('txt', id); 	// 创建文本消息
	    var option = {
	        msg: mes,             					// 消息内容
	        to: toGroupId,                     		// 接收消息对象(群组id)
	        roomType: false,
	        chatType: 'chatRoom',
	        success: function () {
	        	if(fn) fn(id,serverMsgId);
	            console.log('send room text success');
	        },
	        fail: function () {
	            console.log('failed');
	        }
	    };
	    msg.set(option);
	    msg.setGroup('groupchat');
	    IMconn.send(msg.body);
	},
	//添加朋友 发起添加请求
	doAddFriend : function(touser,message){
		console.log(touser)
		console.log(message)
		IMconn.subscribe({
		  	to: touser,
		  	message: message
		});	
	},
	// 删除好友
	removeFriends : function (you) {
	    IMconn.removeRoster({
	        to: you,
	        success: function () {  // 删除成功
	            IMconn.unsubscribed({
	                to: you
	            });
	        },
	        error: function () {    // 删除失败
	        }
	    });
	},
	//好友请求
	handlePresence : function ( e ) {
	  //（发送者希望订阅接收者的出席信息），即别人申请加你为好友
	  if ( e.type === 'subscribe' ) {
	    WebIMFun.tongyiFriend(e.to,e.from);
	    //若e.status中含有[resp:true],则表示为对方同意好友后反向添加自己为好友的消息，demo中发现此类消息，默认同意操作，完成双方互为好友；如果不含有[resp:true]，则表示为正常的对方请求添加自己为好友的申请消息。
	  }
	 
	  //(发送者允许接收者接收他们的出席信息)，即别人同意你加他为好友
	  if ( e.type === 'subscribed' ) {
	 
	  }
	   
	  //（发送者取消订阅另一个实体的出席信息）,即删除现有好友
	  if ( e.type === 'unsubscribe' ) {
	 
	  }
	   
	  //（订阅者的请求被拒绝或以前的订阅被取消），即对方单向的删除了好友
	  if ( e.type === 'unsubscribed' ) {
	 
	  }
	},
	//同意好友申请
	tongyiFriend: function(my,you){ 
	    IMconn.subscribed({
	      	to: my,
	      	message : '[resp:true]'
	    });
	    IMconn.subscribe({//需要反向添加对方好友
	     	to: you,
	      	message : '[resp:true]'
	    });
	},
	//获取聊天记录
	
	doGetTalkLog : function (){
		 
//		$.getJSON();
	},
	//连接成功回调
	onOpened: function ( message ) {
		CS('onOpened',message);
	},  
	//连接关闭回调
	onClosed: function ( message ) { 
		//pageFun.hxLogin();		
		CS('onClosed',message);
	},
	//收到文本消息     
	onTextMessage: function ( message ) {
		CS('onTextMessage',message);
		console.log(message);
//		console.log(message.type);
		if(message.type == "chat"){
			if(message.from == plp){
				pageFun.addMesLog(message);
			}else{
				pageFun.onSubscribe(message);
			}
		}
		if(message.type == "groupchat"){
			if(message.to == plp){
				pageFun.addMesLog(message);
			}else{
				pageFun.onSubscribe(message);
			}
		}
	},    
	onEmojiMessage: function ( message ){
		CS('onEmojiMessage',message);
	},   //收到表情消息
	onPictureMessage: function ( message ){
		console.log(JSON.stringify(message));
		var from_user = fun.getCache("hxUser");
		if(from_user == message.from){
			return false;
		}
		//收到图片消息
		CS('onPictureMessage',message);
		if(message.type == "chat"){
			if(message.from == plp){
				var options = {
					url: message.url,
					onFileDownloadComplete:function (response){
						console.log(response)
				      	var res = URL.createObjectURL(response);
		            	var tmpmessage = {
				      		id:message.id,
				      		type:message.type,
				      		src:res,
				      		from:message.from,
				      		to:message.to,
				      		newsType:"img"
				      	}
				      	pageFun.img_news(tmpmessage);
		      		},
		      		onFileDownloadError:function () {fun.tan("图片下载失败")},
				};
		        WebIM.utils.download.call(IMconn, options);
			}else{
				var options = {
					url: message.url,
					onFileDownloadComplete:function (response){
						var res = URL.createObjectURL(response);
						console.log(response)
		            	var tmpmessage = {
				      		id:message.id,
				      		type:message.type,
				      		src:res,
				      		from:message.from,
				      		to:message.to,
				      		newsType:"img"
				      	}
				      	pageFun.onSubscribe(tmpmessage);
		      		},
		      		onFileDownloadError:function () {fun.tan("图片下载失败")},
				};
		        WebIM.utils.download.call(IMconn, options);
			}
		}
		if(message.type == "groupchat"){
			if(message.to == plp){
				var options = {
					url: message.url,
					onFileDownloadComplete:function (response){
						console.log(response)
				      	var res = URL.createObjectURL(response);
		            	var tmpmessage = {
				      		id:message.id,
				      		type:message.type,
				      		src:res,
				      		from:message.from,
				      		to:message.to,
				      		newsType:"img"
				      	}
		            	hx.post(hx.head_img,{fname:message.from},function(obj){
		            		if(obj.s){
		            			var other = obj.d.other;
						      	pageFun.img_news(tmpmessage,other);
		            		}
		            	})
		      		},
		      		onFileDownloadError:function () {fun.tan("图片下载失败")},
		      		
				};
		        WebIM.utils.download.call(IMconn, options);
			}else{
				console.log(plp);
				console.log(message);
				console.log(JSON.stringify(message));
				console.log("2");
				var options = {
					url: message.url,
					onFileDownloadComplete:function (response){
						var res = URL.createObjectURL(response);
		            	var tmpmessage = {
				      		id:message.id,
				      		type:message.type,
				      		src:res,
				      		from:message.from,
				      		to:message.to,
				      		newsType:"img"
				      	}
				      	pageFun.onSubscribe(tmpmessage);
		      		},
		      		onFileDownloadError:function () {fun.tan("图片下载失败")},
				};
		        WebIM.utils.download.call(IMconn, options);
			}
		}
	}, //收到图片消息
	onCmdMessage: function ( message ){
		CS('onCmdMessage',message);
	},     //收到命令消息
	onAudioMessage: function ( message ){
		CS('onAudioMessage',message);
//		收到语音消息
		console.log(message);
		var from_user = fun.getCache("hxUser");
		if(from_user == message.from){
			return false;
		}
		if(message.type == "chat"){
			if(message.from == plp){
				var options = {
					url: message.url,
					onFileDownloadComplete:function( response ){
				      	var res = URL.createObjectURL(response);
				      	var tmpmessage = {
				      		id:message.id,
				      		type:message.type,
				      		src:res,
				      		from:message.from,
				      		to:message.to,
				      		newsType:"audio"
				      	}
				      	pageFun.Voice(tmpmessage);
				    },
				    onFileDownloadError:function(){},
				    headers:{'Accept':'audio/mp3'}
				};
			    WebIM.utils.download.call(IMconn, options);
			}else{
				var options = {
					url: message.url,
					onFileDownloadComplete:function( response ){
				      	var res = URL.createObjectURL(response);
				      	var tmpmessage = {
				      		id:message.id,
				      		type:message.type,
				      		src:res,
				      		from:message.from,
				      		to:message.to,
				      		newsType:"audio"
				      	}
				      	pageFun.onSubscribe(tmpmessage);
				    },
				    onFileDownloadError:function(){},
				    headers:{'Accept':'audio/mp3'}
				}; 
			    WebIM.utils.download.call(IMconn, options);
			}
		}
		if(message.type == "groupchat"){
			if(message.to == plp){
				var options = {
					url: message.url,
					onFileDownloadComplete:function( response ){
				      	var res = URL.createObjectURL(response);
				      	var tmpmessage = {
				      		id:message.id,
				      		type:message.type,
				      		src:res,
				      		from:message.from,
				      		to:message.to,
				      		newsType:"audio"
				      	}
				      	hx.post(hx.head_img,{fname:message.from},function(obj){
							if(obj.s){
								var VoiceHeadImg = obj.d.other;
								var VoiceHeadImg2 = obj.d.my;
						      	pageFun.Voice(tmpmessage,VoiceHeadImg);
							}
						});
				    },
				    onFileDownloadError:function(){},
				    headers:{'Accept':'audio/mp3'}
				}; 
			    WebIM.utils.download.call(IMconn, options);
			}else{
				var options = {
					url: message.url,
					onFileDownloadComplete:function( response ){
				      	var res = URL.createObjectURL(response);
				      	var tmpmessage = {
				      		id:message.id,
				      		type:message.type,
				      		src:res,
				      		from:message.from,
				      		to:message.to,
				      		newsType:"audio"
				      	}
				      	pageFun.onSubscribe(tmpmessage);
				    },
				    onFileDownloadError:function(){},
				    headers:{'Accept':'audio/mp3'}
				}; 
			    WebIM.utils.download.call(IMconn, options);
			}
		}
	},   //收到音频消息
	onLocationMessage: function ( message ) {
		CS('onLocationMessage',message);
	},//收到位置消息
	onFileMessage: function ( message ) {
		CS('onFileMessage',message);
	},    //收到文件消息
	onVideoMessage: function ( message ) {
		CS('onVideoMessage',message);
	},   //收到视频消息
	onPresence: function ( message ) {
		console.log(message);
		pageFun.onSubscribe(message);
		CS('onPresence',message); 
		CS('onPresence','收到联系人订阅请求、处理群组、聊天室被踢解散等消息');
	},       //收到联系人订阅请求、处理群组、聊天室被踢解散等消息
	onRoster: function ( message ) {
		CS('onRoster',message);
		CS('onRoster','处理好友申请');
	},         //处理好友申请
	onInviteMessage: function ( message ) {
		CS('onInviteMessage',message);
	},  //处理群组邀请
	
	onOnline: function () {
		CS('onOnline','');
	},                  //本机网络连接成功
	onOffline: function () {
		CS('onOffline','');
	},                 //本机网络掉线
	onError: function ( message ) {
		//pageFun.hxLogin();
		CS('onError',message);
	}           //失败回调

}

function InitWebIM(){
	IMconn = new WebIM.connection({
			https: WebIM.config.https,
			url: WebIM.config.xmppURL,
			isAutoLogin: WebIM.config.isAutoLogin,
			isMultiLoginSessions: WebIM.config.isMultiLoginSessions
		});
	IMconn.listen({
			onOpened: function ( message ) {          	//连接成功回调
				//如果isAutoLogin设置为false，那么必须手动设置上线，否则无法收消息
				IMconn.setPresence();
				CS('onOpen',message);
				WebIMFun.onOpened(message);
			},
			onClosed: function ( message ) {			//连接关闭回调
				WebIMFun.onClosed(message);
			},
			onTextMessage: function ( message ) {		//收到文本消息
				WebIMFun.onTextMessage(message);
			},
			onEmojiMessage: function ( message ) {		//收到表情消息
				WebIMFun.onEmojiMessage(message);
			},
			onPictureMessage: function ( message ) {	//收到图片消息
				WebIMFun.onPictureMessage(message);
			},
			onCmdMessage: function ( message ) {		//收到命令消息
				WebIMFun.onCmdMessage(message);
			},     
			onAudioMessage: function ( message ) {		//收到音频消息
				WebIMFun.onAudioMessage(message);
			},   
			onLocationMessage: function ( message ) {	//收到位置消息
				WebIMFun.onLocationMessage(message);
			},
			onFileMessage: function ( message ) {		//收到文件消息
				WebIMFun.onFileMessage(message);
			},    
			onVideoMessage: function ( message ) {		//收到视频消息
				WebIMFun.onVideoMessage(message);
			},   
			onPresence: function ( message ) {			//收到联系人订阅请求、处理群组、聊天室被踢解散等消息
				WebIMFun.onPresence(message);
			},       
			onRoster: function ( message ) {			//处理好友申请
				WebIMFun.onRoster(message);
			},         
			onInviteMessage: function ( message ) {		//处理群组邀请
				WebIMFun.onInviteMessage(message);
			},  
			onOnline: function () {						//本机网络连接成功
				WebIMFun.onOnline();
			},                  
			onOffline: function () {					//本机网络掉线
				WebIMFun.onOffline();
			},                 
			onError: function ( message ) {				//失败回调
				WebIMFun.onError(message);
			}           
		});
}